package org.zero.concurrency.demo.example.atomic;

import lombok.extern.slf4j.Slf4j;
import org.zero.concurrency.demo.annotations.ThreadSafe;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @program: concurrency-demo
 * @description: 模拟并发执行
 * @author: 01
 * @create: 2018-10-14 00:01
 **/
@Slf4j
@ThreadSafe
public class AtomicExample2 {

    /**
     * 请求总数
     */
    public static int clientTotal = 5000;

    /**
     * 同时并发执行的线程数量
     */
    public static int threadTotal = 200;

    /**
     * 计数
     */
    private static AtomicLong count = new AtomicLong(0);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(threadTotal);
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    // 从信号量获取执行许可，若并发达到设定的数量，那么就不会获取到许可，将会阻塞当前线程，直到能够获取到执行许可为止
                    semaphore.acquire();
                    AtomicExample2.add();
                    // 释放当前线程
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("", e);
                }
                countDownLatch.countDown();
            });
        }

        countDownLatch.await();
        executorService.shutdown();
        log.info("count: {}", count.get());
    }

    private static void add() {
        // 先+1，然后获取当前的值，类似于++count
        count.incrementAndGet();
    }
}
